﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;

namespace JobPauseAndResume.ViewModels
{
    public partial class MainWindowViewModel : ObservableObject
    {
        Channel<Task> channel = Channel.CreateUnbounded<Task>(); 

        [ObservableProperty]
        public string buttonContent = "暂停";

        public MainWindowViewModel()
        {
            _ = DoSomethingAsync();
        }

        async Task DoSomethingAsync()
        {
            Task.Run(async () =>
            {
                while (true)
                {
                    Task task = Checkout();
                    if (task != null)
                    {
                        task.Wait();
                    }

                    await Task.Delay(1000);
                    Console.WriteLine("Doing something...");
                }
            });
        }

        public Task Checkout()
        {
            channel.Reader.TryRead(out var task);
            return (Task)task;
        }

        TaskCompletionSource taskCompletionSource = new TaskCompletionSource();

        [RelayCommand]
        async Task Button()
        {

            if (ButtonContent == "暂停")
            {
                taskCompletionSource = new TaskCompletionSource();
                channel.Writer.TryWrite(taskCompletionSource.Task);
                ButtonContent = "继续";
            }
            else
            {
                taskCompletionSource.TrySetResult();
                ButtonContent = "暂停";
            }
        }
    }
}
